package edu.szte.ovrt.datahandler.ui.console;

import edu.szte.ovrt.datahandler.model.Item;
import edu.szte.ovrt.datahandler.model.Section;

/**
 * Menu state for {@link Section} level.
 * 
 * @author Peter
 */
public class EditSection extends Menu {
	protected final Section m_section;

	public EditSection(final Section section) {
		m_section = section;
		initialize();
	}

	public Section getSection() {
		return m_section;
	}

	protected void initialize() {

		m_menuMap.add("List content", new IAction() {

			@Override
			public void run() throws ExitAction {
				newScreen("CONTENT OF [" + m_section.getName() + "]");
				System.out.printf("[%s]\n", m_section.getName());
				for (final Item i : m_section.getItems()) {
					System.out.printf("   %s = %s\n", i.getKey(), i.getValue());
				}
				showMessage("Press [ENTER] key to continue.");
				readInt();
			}
		});

		m_menuMap.add("Edit name of section", new IAction() {

			@Override
			public void run() throws ExitAction {
				final String newName = (new Dialog("New name", true)).getValue();
				if (newName.length() != 0) {
					m_section.setName(newName);
				} else {
					showError("Name cannot be empty.");
				}
			}
		});

		m_menuMap.add("Add new item", new IAction() {
			@Override
			public void run() throws ExitAction {
				final String newItemKey = (new Dialog("Key", true)).getValue();
				final String newItemValue = (new Dialog("Value", true)).getValue();
				if (newItemKey.length() != 0) {
					m_section.newItem(newItemKey, newItemValue);
				} else {
					showError("The item's name cannot be empty.");
				}
			}
		});

		m_menuMap.add("Edit item", new IAction() {

			@Override
			public void run() throws ExitAction {
				final Item item = (new Selector<Item>(m_section.getItems())).getSelection();
				(new EditItem(item)).run();
			}
		});

		m_menuMap.add("Delete item", new IAction() {

			@Override
			public void run() throws ExitAction {
				try {
					final Item item = (new Selector<Item>(m_section.getItems())).getSelection();
					if (m_section.getItems().remove(item)) {
						showMessage("Successfully deleted.");
					} else {
						showError("Deletion failed.");
					}
				} catch (final ExitAction e) {
					// NOOP
				}
			}
		});

		m_menuMap.addExit("Back to document level");
	}

	@Override
	protected String getTitle() {
		return "Section [" + m_section.getName() + "]";
	}

}
